#!/usr/bin/env
#-*- encoding:utf-8 -*-

from PyQt5.QtCore import *

import re

class FSortFilterModel(QSortFilterProxyModel):
    def __init__(self, parent = None):
        super(FSortFilterModel,self).__init__(parent)

        self.column_filters = {}
        self.or_mode = True

    def add_filter_column(self,column_num,column_pattern):
        """
        为某一列添加一个过滤器
        :param column_num:
        :param column_pattern: 符合标准正则规则的过滤模式
        :return:
        """
        self.column_filters[column_num] = re.compile(column_pattern)

    def clear_filters(self):
        self.column_filters.clear()

    def set_filter_mode(self,or_mode):
        self.or_mode = or_mode

    def filterAcceptsRow(self, source_row, source_parent):
        if len(self.column_filters) == 0:
            return True
        filter_result = False
        if self.or_mode:
            for column_num, column_filter in self.column_filters.items():
                if filter_result:
                    break
                source_model_index = self.sourceModel().index(source_row,column_num,source_parent)
                source_model_index_data = source_model_index.data()
                if isinstance(source_model_index_data, str):
                    search_result = column_filter.search(source_model_index_data)
                    if search_result is not None:
                        filter_result = True
                        break
                elif isinstance(source_model_index_data, list):
                    for source_model_index_data_cell in source_model_index_data:
                        search_result = column_filter.search(str(source_model_index_data_cell))
                        if search_result is not None:
                            filter_result = True
                            break
        else:  # 且模式还未实现
            raise NotImplementedError
        return filter_result